<template>
  <div>
    <h2>vue3 + TypeScript</h2>

    <h4>计数器</h4>
    <button @click="minus">-</button>
    <span>{{ count }}</span>
    <button @click="add()">+1</button>
    <button @click="add(2)">+2</button>
    <button @click="add(3)">+3</button>
    <div>doubleCount: {{ doubleCount }}</div>

    <h4>todolist</h4>
    <input type="text" v-model="textValue" />
    <button @click="push">添加</button>
    <ul>
      <li v-for="item in list" :key="item.id">
        {{ item.name }} - <button @click="remove(item.id)">删除</button>
      </li>
    </ul>
    <input type="text" @input="fn" />

    <h4>列表渲染</h4>
    <ul>
      <li v-for="item in arr" :key="item.proid">{{ item.proname }}</li>
    </ul>

    <hr />

    <Child :count="count" name="tom" @abc="fn3" />
  </div>
</template>

<script lang="ts" setup>
// import的引入不需要ts类型
import {
  ref,
  computed,
  watch,
  onMounted,
  reactive,
  provide,
  inject,
} from "vue";

import Child from "./Child.vue";

// ref创建的变量需要使用泛型的语法来添加类型
const count = ref<number>(10);
// computed的类型和ref一样用泛型来添加
const doubleCount = computed<number>(() => count.value * 2);
// watch监听的时候通常不需要加类型
watch(count, (val: number): void => {
  console.log("count改变成了" + val);
});

// 定义函数的时候，可以省略函数的类型，函数返回值的类型最好写
const add = (n: number = 1): void => {
  count.value += n;
};
const minus = (): void => {
  count.value--;
};

interface ListItemType {
  id: number;
  name: string;
}
const list = ref<ListItemType[]>([
  {
    id: 1,
    name: "zhangsan",
  },
  {
    id: 2,
    name: "lisi",
  },
]);
const textValue = ref<string>("");
const push = (): void => {
  // console.log(textValue.value);
  list.value.push({
    id: new Date().getTime(),
    name: textValue.value,
  });
};
const remove = (id: number): void => {
  list.value = list.value.filter((item) => item.id !== id);
};
const fn = (e: Event) => {
  // as表示断言
  console.log((e.target as HTMLInputElement).value);
};

interface ArrItemType {
  proid: string;
  proname: string;
  [propName: string]: any;
}
const arr = ref<ArrItemType[]>([]);
onMounted(() => {
  fetch("http://121.89.205.189:3000/api/pro/list")
    .then((response) => response.json())
    .then((res) => {
      console.log(res);
      arr.value = res.data;
    });
});

interface StateType {
  a: number;
  b: number;
}
const state = reactive<StateType>({
  a: 4,
  b: 5,
});

provide("name", "zhangsan");
const name: string | undefined = inject("name");

const fn3 = (n: number) => {
  console.log("fn3", n);
};
</script>
